﻿using System;
using System.ComponentModel;

namespace Fuse8.ContentManagementFramework.Web.MvcPowered
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public class NewPasswordAndConfirmationMustMatchAttribute : PropertiesMustMatchAttribute
    {
        public string CurrentPasswordProperty { get; protected set; }

        public NewPasswordAndConfirmationMustMatchAttribute(string originalProperty, string confirmProperty, string currentPasswordProperty)
            : base(originalProperty, confirmProperty)
        {
            CurrentPasswordProperty = currentPasswordProperty;
        }

        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);

            object currentPassword = !string.IsNullOrEmpty(CurrentPasswordProperty) ?
                properties.Find(CurrentPasswordProperty, true /* ignoreCase */).GetValue(value) :
                null;

            object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);

            return currentPassword == null ?
                base.IsValid(value) :
                (originalValue != null) && !string.IsNullOrEmpty(originalValue.ToString()) && base.IsValid(value);
        }
    }
}
